package net.yxsoft.controller.pc.sysmgt.infrastructure;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import net.yxsoft.bean.JsTreeNodeFieldKey;
import net.yxsoft.controller.pc.sysmgt.common.AuthController;
import net.yxsoft.controller.pc.sysmgt.common.interceptor.AuthInterceptor;
import net.yxsoft.controller.pc.sysmgt.common.interceptor.LoginDbSessionInterceptor;
import net.yxsoft.controller.pc.sysmgt.common.validator.LoginValidator;
import net.yxsoft.kit.JsTreeNodeKit;
import net.yxsoft.kit.QRCodeKit;
import net.yxsoft.kit.wbdata;
import net.yxsoft.model.infrastructure.TsMenu;
import net.yxsoft.quorum.QuorumKit;
import net.yxsoft.resource.AuthuserRes;
import net.yxsoft.resource.PathRes;
import net.yxsoft.resource.Res;
import net.yxsoft.service.infrastructure.LoginService;
import rapid.core.Authuser;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @MethodName: IndexController
* @Description:
* @param: null
* @return * @return null
* @throws
* @date 2023/8/31 15:28
* @author jhf
*/
public class IndexController extends AuthController {

  private static final LoginService srv = LoginService.INSTANCE;
  /**
  * @MethodName: index
  * @Description:
  * @param:
  * @return void
  * @throws
  * @date 2023/8/31 15:28
  * @author jhf
  */
  @Clear(AuthInterceptor.class)
  public void index() throws Exception {


    Map m = new HashMap<>();
    Authuser loginUser = getLoginUser();

    if (null != loginUser) {
      List<TsMenu> menus = srv.findModuleAndApp(getLoginUser().getId());//二级菜单内容
      List<TsMenu> oneMenus = srv.findOneModuleAndApp(getLoginUser().getId());//获取一级菜单
      set("oneMenus",oneMenus);
      set("menus",menus);
      setAttr("loginUser", loginUser);
      render("/pc/sysmgt/block/index_new.html");

    } else {
      render("login.html");
    }
  }



  /**
  * @MethodName: toLogin
  * @Description:
  * @param:
  * @return void
  * @throws
  * @date 2023/8/31 15:28
  * @author jhf
  */
  @Clear({LoginDbSessionInterceptor.class, AuthInterceptor.class})
  @Before({POST.class, LoginValidator.class})
  public void toLogin() throws Exception {

    result = srv.login(getPara("loginId"), getPara("loginIds"), getPara("keepLogin", "").equals("on"));

    if (result.isSuccess()) {
      setCookie(AuthuserRes.KEY_TS_SESSION_UID, result.get(AuthuserRes.KEY_TS_SESSION_UID),result.get(Res.MAX_AGEIN_SECONDS), true);
      setSessionAttr(AuthuserRes.KEY_LOGIN_TYPE, 1);
      setSessionAttr(Authuser.KEY_USER, result.get(Authuser.KEY_USER));
      removeCookie(AuthuserRes.KEY_JSESSIONID);
    }

    renderJson(result);
  }
  /**
  * @MethodName: logout
  * @Description:
  * @param:
  * @return void
  * @throws
  * @date 2023/8/31 15:28
  * @author jhf
  */
  @Clear
  public void logout() {
    clearUser();

    redirect(PathRes.URL_PC_MGT_ROOT);
  }
  /**
  * @MethodName: updateUserPwd
  * @Description:
  * @param:
  * @return void
  * @throws
  * @date 2023/8/31 15:28
  * @author jhf
  */
  @Before(POST.class)
  public void updateUserPwd() {
    Authuser user = getLoginUser();

    if (user == null) {
      sessionTimeout();

    } else {
      renderJson(srv.updateUserPwd(user.getLoginId(), getPara("oldPwd"), getPara("newPwd"), getPara("confirmPwd")));
    }
  }

  /**
  * @MethodName: findModuleAndApp
  * @Description: 查找用户可访问的菜单（不包括功能）
  * @param:
  * @return void
  * @throws
  * @date 2023/8/31 15:28
  * @author jhf
  */
  @Before(POST.class)
  public void findModuleAndApp() throws NoSuchMethodException, SecurityException, InvocationTargetException, IllegalAccessException {
    Authuser user = getLoginUser();

    if (user == null) {

      sessionTimeout();

    } else {
      List<TsMenu> menus = srv.findModuleAndApp(Res.DEV_MODE ? null : user.getId());
      List<TsMenu> oneMenus = srv.findOneModuleAndApp(Res.DEV_MODE ? null : user.getId());
      menus.addAll(oneMenus);
      if (Res.DEV_MODE || "admin".equals(user.getLoginId())) {

        menus.add(new TsMenu() {
          {
            setId(Integer.MAX_VALUE);
            setName("开发者菜单");
            setPid(0);
          }
        });

        menus.add(new TsMenu() {
          {
            setId(Integer.MAX_VALUE - 1);
            setName("模型管理|" + PathRes.URL_PC_MGT_ROOT + "/dataModel");
            setPid(Integer.MAX_VALUE);
          }
        });

        menus.add(new TsMenu() {
          {
            setId(Integer.MAX_VALUE - 2);
            setName("菜单管理|" + PathRes.URL_PC_MGT_ROOT + "/menu");
            setPid(Integer.MAX_VALUE);
          }
        });

      }


      JsTreeNodeFieldKey tnfk = new JsTreeNodeFieldKey("Id", "Name", "Pid");
      tnfk.setLeafKey("Pid");
      tnfk.setLeafValue("0");

      renderJson(JsTreeNodeKit.SerializeJsTreeData(tnfk, menus));
    }
  }
  /**
  * @MethodName: clearUser
  * @Description:
  * @param:
  * @return void
  * @throws
  * @date 2023/8/31 15:28
  * @author jhf
  */
  private void clearUser() {
    srv.logout(getCookie(AuthuserRes.KEY_TS_SESSION_UID));

    removeCookie(AuthuserRes.KEY_TS_SESSION_UID);
    removeSessionAttr(Authuser.KEY_USER);
    removeCookie(AuthuserRes.KEY_JSESSIONID);
  }



}
